package redis

import (
	"context"
	"encoding/json"
	"errors"
	"strconv"

	"github.com/go-redis/redis/v8"
)

func InitRedis(config string) (standaloneRedis *redis.Client, err error) {
	var cf map[string]string
	err = json.Unmarshal([]byte(config), &cf)
	if err != nil {
		return
	}

	if _, ok := cf["conn"]; !ok {
		err = errors.New("config has no conn key")
		return
	}

	// db库
	dbNum := 0
	// 如果指定了db库
	if _, ok := cf["dbNum"]; ok {
		dbNum, err = strconv.Atoi(cf["dbNum"])
		if err != nil {
			return
		}
	}

	// 密码
	if _, ok := cf["password"]; !ok {
		cf["password"] = ""
	}

	client := redis.NewClient(&redis.Options{
		Addr:     cf["conn"],
		Password: cf["password"],
		DB:       dbNum,
		//PoolSize: 10, //连接池最大socket连接数，默认为10倍CPU数， 10 * runtime.NumCPU（暂不配置）
	})

	_, err = client.Ping(context.TODO()).Result()
	if err != nil {
		err = errors.New("redis 链接失败:" + err.Error())
		return
	}

	standaloneRedis = client

	return
}
